package com.lyEducation.controllers.video;

import com.lyEducation.controllers.base.BaseController;
import com.lyEducation.controllers.dto.UserVideoCommentDto;
import com.lyEducation.core.base.SysConstants;
import com.lyEducation.core.video.VideoQueryEnum;
import com.lyEducation.core.video.VideoService;
import com.lyEducation.entities.middle.userVideo.UserVideoCommentClickPraiseEntity;
import com.lyEducation.entities.middle.userVideo.UserVideoCommentEntity;
import com.lyEducation.entities.middle.userVideo.UserVideoScoreEntity;
import com.lyEducation.entities.video.VideoEntity;
import com.lyEducation.repository.VideoRepository;
import com.lyEducation.security.config.SecurityPrincipalContext;
import com.lyEducation.util.StringUtils;
import com.lyEducation.util.controllerUtil.JsonConstans;
import com.lyEducation.util.controllerUtil.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Api(value = "视频", tags = {"视频模块接口,{mId}菜单id"}, description = "视频模块接口")
@RestController
@RequestMapping("video/{mid}")
@Transactional(rollbackFor = Exception.class, readOnly = false, propagation = Propagation.REQUIRED)
public class VideoController extends BaseController<VideoEntity> {
    @Autowired
    private VideoRepository videoRepository;
    @Autowired
    private VideoService videoService;

    @ApiOperation(value = "视频热推首页", notes = "视频热推首页")
    @Override
    public JsonResult onLoad() {
        return JsonResult.putSuccess(videoService.findData(VideoQueryEnum.NEW));
    }

    @ApiOperation(value = "视频热推首页", notes = "视频热推首页")
    @ApiImplicitParam(
            name = "queryPage",
            value = "分页查询视频信息",
            required = true,
            dataType = "QueryPage",
            paramType = "body"
    )
    @PostMapping("selVideosByType")
    public JsonResult selVideosByType(@RequestBody QueryPage queryPage) {
        Map map = new HashMap();
        map.put("type", queryPage.getType());
        return JsonResult.putSuccess(
                videoRepository.findPageByNativeQueryFileds(
                        "select * from video where type=:type and videoAccessRole=0",
                        map,
                        queryPage.getPageNo(),
                        queryPage.getPageSize()));
    }

    @ApiOperation(value = "显示视频评论", notes = "显示视频评论")
    @ApiImplicitParam(
            name = "videoId",
            value = "视频id",
            required = true,
            dataType = "String",
            paramType = "body"
    )
    @GetMapping("selVideoCommentByVideoId/{videoId}")
    public JsonResult selVideoComment(@PathVariable String videoId) {
        Map<String, Object> map = new HashMap();
        map.put("videoId", videoId);

        map = videoRepository.findPageByNativeQueryFileds(
                "SELECT uvc.id,uvc.videoId,uvc.score, uvc.`comment`,su.`name` as name ,uvc.parentId,uvc.sort FROM user_video_comment as uvc LEFT JOIN sys_user as su on uvc.id=su.id where uvc.videoId=:videoId",
                map, Transformers.aliasToBean(UserVideoCommentDto.class),
                null,
                null);
        List<UserVideoCommentDto> userVideoCommentDtos = (List<UserVideoCommentDto>) map.get(SysConstants.ROWS.getValue());


//        UpDownTreeEntityService<UserVideoCommentDto> upDownTreeEntityService =
//                UpDownTreeEntityServiceImpl.createUpDownTreeEntityService(UserVideoCommentDto.class);
//        upDownTreeEntityService.upDownTreeEntity(userVideoCommentDtos);
        return JsonResult.putSuccess(UserVideoCommentDto.upDownTreeEntity(userVideoCommentDtos));
    }

    @ApiOperation(value = "添加更新视频评论", notes = "添加更新视频评论")
    @PostMapping("addUpdVideoComment")
    public JsonResult addUpdVideoComment(@RequestBody UserVideoCommentEntity userVideoCommentEntity) {
        userVideoCommentEntity.setId(SecurityPrincipalContext.getUserDetailsImpl().getId());
        if (StringUtils.isNotBlank(userVideoCommentEntity.getVideoId())) {
            if (StringUtils.isNotBlank(userVideoCommentEntity.getId())) {
                videoRepository.update(userVideoCommentEntity);
                return JsonResult.putSuccess();
            } else {
                videoRepository.save(userVideoCommentEntity);
                return JsonResult.putSuccess();
            }
        }
        return JsonResult.putFail(JsonConstans.ERR_NOTVALID_AUTH);
    }

    @ApiOperation(value = "删除视频评论", notes = "删除视频评论")
    @GetMapping("delVideoComment/{videoId}")
    public JsonResult delVideoComment(@PathVariable String videoId) {
        if (StringUtils.isNotBlank(videoId)) {
            Map<String, Object> map = new HashMap();
            map.put("userId", SecurityPrincipalContext.getUserDetailsImpl().getId());
            map.put("videoId", videoId);
            videoRepository.deleteByMap(UserVideoCommentEntity.class, map);
            return JsonResult.putSuccess();
        }
        return JsonResult.putFail(JsonConstans.ERR_NOTVALID_AUTH);
    }

    @ApiOperation(value = "添加用户视频评论点赞", notes = "添加用户视频评论点赞")
    @GetMapping("addUserVideoCommentClickPraise/{commentId}")
    public JsonResult addUserVideoCommentClickPraise(@PathVariable String commentId) {
        UserVideoCommentClickPraiseEntity userVideoCommentClickPraiseEntity = new UserVideoCommentClickPraiseEntity();
        userVideoCommentClickPraiseEntity.setCommentId(commentId);
        userVideoCommentClickPraiseEntity.setUserId(SecurityPrincipalContext.getUserDetailsImpl().getId());
        videoRepository.save(userVideoCommentClickPraiseEntity);
        UserVideoCommentEntity userVideoCommentEntity = videoRepository.findById(UserVideoCommentEntity.class, commentId);
        userVideoCommentEntity.setScore((userVideoCommentEntity.getSort() + 1));
        videoRepository.update(userVideoCommentEntity);
        return JsonResult.putSuccess();
    }

    @ApiOperation(value = "删除用户视频评论点赞", notes = "删除用户视频评论点赞")
    @GetMapping("delUserVideoCommentClickPraise/{commentId}")
    public JsonResult delUserVideoCommentClickPraise(@PathVariable String commentId) {
        LinkedHashMap<String, Object> linkedHashMap = new LinkedHashMap<>();
        linkedHashMap.put("commentId", commentId);
        linkedHashMap.put("userId", SecurityPrincipalContext.getUserDetailsImpl().getId());
        videoRepository.deleteByMap(UserVideoCommentClickPraiseEntity.class, linkedHashMap);
        UserVideoCommentEntity userVideoCommentEntity = videoRepository.findById(UserVideoCommentEntity.class, commentId);
        userVideoCommentEntity.setScore((userVideoCommentEntity.getSort() - 1));
        videoRepository.update(userVideoCommentEntity);
        return JsonResult.putSuccess();
    }

//    @GetMapping("addUserVideoClickPraise/{videoId}")
//    public JsonResult addUserVideoClickPraise(@PathVariable String videoId) {
//
//        if (StringUtils.isNotBlank(videoId)) {
//            UserVideoClickPraiseEntity userVideoClickPraiseEntity = new UserVideoClickPraiseEntity();
//            userVideoClickPraiseEntity.setUserId(SecurityPrincipalContext.getUserDetailsImpl().getId());
//            userVideoClickPraiseEntity.setVideoId(videoId);
//            videoRepository.save(userVideoClickPraiseEntity);
//            return JsonResult.putSuccess();
//        }
//        return JsonResult.putFail(JsonConstans.ERR_NOTVALID_AUTH);
//    }
//
//    @GetMapping("delUserVideoClickPrais/{videoId}")
//    public JsonResult delUserVideoClickPraise(@PathVariable String videoId) {
//        if (StringUtils.isNotBlank(videoId)) {
//            Map<String, Object> map = new HashMap();
//            map.put("userId", SecurityPrincipalContext.getUserDetailsImpl().getId());
//            map.put("videoId", videoId);
//            videoRepository.deleteByMap(UserVideoClickPraiseEntity.class, map);
//            return JsonResult.putSuccess();
//        }
//        return JsonResult.putFail(JsonConstans.ERR_NOTVALID_AUTH);
//    }

    @ApiOperation(value = "添加用户视频评分", notes = "添加用户视频评分")
    @PostMapping("addUserVideoScore")
    public JsonResult addUserVideoScore(@RequestBody UserVideoScoreEntity userVideoScoreEntity) {
        if (StringUtils.isNotBlank(userVideoScoreEntity.getVideoId())) {
            userVideoScoreEntity.setUserId(SecurityPrincipalContext.getUserDetailsImpl().getId());
            videoRepository.save(userVideoScoreEntity);
            return JsonResult.putSuccess();
        }
        int score = userVideoScoreEntity.getScore();
        VideoEntity videoEntity = videoRepository.findById(userVideoScoreEntity.getVideoId());

        List<UserVideoScoreEntity> userVideoScoreEntities =
                videoRepository.findByFiled(
                        UserVideoScoreEntity.class, "videoId", userVideoScoreEntity.getVideoId());
        BigDecimal scoreB = BigDecimal.valueOf(score);
        BigDecimal totalScore = BigDecimal.valueOf(videoEntity.getTotalScore());

        return JsonResult.putFail(JsonConstans.ERR_NOTVALID_AUTH);
    }

    @ApiOperation(value = "更新用户视频评分", notes = "更新用户视频评分")
    @PostMapping("updUserVideoScore")
    public JsonResult updUserVideoScore(@RequestBody UserVideoScoreEntity userVideoScoreEntity) {
        userVideoScoreEntity.setUserId(SecurityPrincipalContext.getUserDetailsImpl().getId());
        if (StringUtils.isNotBlank(userVideoScoreEntity.getId())) {
            videoRepository.update(userVideoScoreEntity);
            return JsonResult.putSuccess();
        } else if (StringUtils.isNotBlank(userVideoScoreEntity.getVideoId())) {
            videoRepository.save(userVideoScoreEntity);
            return JsonResult.putSuccess();
        }
        return JsonResult.putFail(JsonConstans.ERR_NOTVALID_AUTH);
    }
}
